<template>
  <div id="userRegisterPage">
    <h1>用户注册</h1>

    <el-form :model="form" ref="formRef" label-width="80px">
      <el-form-item label="账号" prop="userAccount">
        <el-input v-model="form.userAccount" clearable placeholder="账号应不少于 4 个字符" />
      </el-form-item>
      <el-form-item label="密码" prop="userPassword">
        <el-input v-model="form.userPassword" show-password autocomplete="off" placeholder="密码应不少于 6 个字符" />
      </el-form-item>
      <el-form-item label="确认密码" prop="checkPassword">
        <el-input v-model="form.checkPassword" show-password autocomplete="off" placeholder="请确认密码" />
      </el-form-item>
    </el-form>

    <el-row id="userRegisterButtons" :gutter="20">
      <el-col :span="12" :offset="0">
        <el-button type="primary" size="large" @click="router.push('/user/login')" plain>直接登录</el-button>
      </el-col>
      <el-col :span="12" :offset="0">
        <el-button type="primary" size="large" @click="doRegister" :loading="registerButtonIsLoading">提交注册</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from "element-plus";
import { reactive, ref } from "vue";
import { userRegisterUsingPost } from "@/api/userController";
import { useRouter } from "vue-router";
import { useLoginUserStore } from "@/stores/userStore";
import { ResponseCodeEnum } from "@/enums";

const router = useRouter();
const loginUserStore = useLoginUserStore();

const form = reactive<API.UserRegisterRequest>({
  userAccount: "",
  userPassword: "",
  checkPassword: "",
});

const registerButtonIsLoading = ref(false);

/**
 * 提交
 */
const doRegister = async () => {
  // 尝试注册
  registerButtonIsLoading.value = true;
  const result = await userRegisterUsingPost(form);
  registerButtonIsLoading.value = false;

  if (result.data.code === ResponseCodeEnum.SUCCESS) {
    // 注册成功, 则刷新用户信息, 并重定向到首页
    loginUserStore.loginUser = result.data.data as API.LoginUserVO;

    ElMessage.success("登录成功");
    router.replace("/");
  } else {
    ElMessage.error("登录失败: " + result.data.message);
  }
};
</script>

<style scoped>
#userRegisterPage {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  width: 100%;
  height: 100%;
}

#userRegisterPage .el-form {
  width: 100%;
}

#userRegisterButtons {
  width: 100%;
}

.el-button {
  width: 100%;
}
</style>
